package com.vecharm.app.wiget

import android.util.Log
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import com.ling.sdk.app.App
import com.pili.pldroid.player.AVOptions
import com.pili.pldroid.player.widget.PLVideoTextureView
import com.vecharm.app.utils.message

class PLPlayer : IPayer {
    override fun onResume() {}

    override fun onPause() {}

    private var videoView: PLVideoTextureView? = null

    private var callback: ((String) -> Unit)? = null

    override fun initPlayer(parent: FrameLayout, url: String) {

        if (videoView == null) {
            videoView = PLVideoTextureView(parent.context)
        }

        (videoView?.parent as? ViewGroup)?.removeView(videoView)

        val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        params.gravity = Gravity.CENTER

        parent.addView(videoView, 0, params)

        videoView?.setAVOptions(options)
        videoView?.isLooping = true
        videoView?.setOnErrorListener {
            callback?.invoke(message[it] ?: "$it:UNKNOWN ERROR")
            return@setOnErrorListener true
        }
//        if (url.isEmpty()) url = "http://oh4yf3sig.cvoda.com/cWEtZGlhbmJvdGVzdDpY54m56YGj6ZifLumfqeeJiC5IRGJ1eHVhbnppZG9uZzAwNC5tcDQ=_q00030002.mp4"
//        if (url.isEmpty()) url = "http://ss.bscstorage.com/95xiu/live/20181009/418013_15390289883806.mp4"
//        if (url.isEmpty()) url = "http://qianfan-qianfanyun.qiniudn.com/_20180201101259_5a7277ab8c2d2.mp4"
        videoView?.setVideoPath(url)

    }

    override fun setOnErrorListener(callback: (String) -> Unit) {
        this.callback = callback
    }


    override fun play() {
        videoView?.start()
    }

    override fun pause() {
        if (videoView?.canPause() == true)
            videoView?.pause()
    }

    override fun stop() {
        videoView?.stopPlayback()
        videoView = null
        callback = null
    }

    companion object {


        val options = AVOptions().also { options ->
            // the unit of timeout is ms
            options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 30 * 1000)
            options.setInteger(AVOptions.KEY_LIVE_STREAMING, 0)
            // 1 -> hw codec enable, 0 -> disable [recommended]
            options.setInteger(AVOptions.KEY_MEDIACODEC, AVOptions.MEDIA_CODEC_AUTO)
            options.setInteger(AVOptions.KEY_LOG_LEVEL, 0) // disableLog = 5
            options.setString(AVOptions.KEY_CACHE_DIR, App.app.externalCacheDir.absolutePath)
            // 快开模式，启用后会加快该播放器实例再次打开相同协议的视频流的速度
            options.setInteger(AVOptions.KEY_FAST_OPEN, 1)
            // 打开重试次数，设置后若打开流地址失败，则会进行重试
            options.setInteger(AVOptions.KEY_OPEN_RETRY_TIMES, 100)

        }
    }
}